<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<view class="data-list">
			<view class="search">
				<uni-datetime-picker type="date" :clear-icon="false" v-model="pickerDate" @change="changeTime" />
			</view>
			<u-line margin="5rpx 0rpx 0rpx 0rpx" />
						<u-sticky v-if="reportRepair"><u-button type="primary" @click="reportRepairClick"
								text="点击提报 [报修申请]"></u-button></u-sticky>
			<u-line margin="5rpx 0rpx 0rpx 0rpx" />
			<view class="item" v-for="(item,index) in deviceSpotList" :key="index">
				<view class="item-title">保养项名称：{{item.mname}}</view>
				<view class="item-body">
					<!-- <view>保养类型：<dict-tag :type="DICT_TYPE.DEVICE_MAINTENANCE_PLAN_TYPE" :value="item.mtype"></dict-tag></view> -->
					<view>工时(时)：{{item.mworkHours}}</view>
					<view>保养内容：{{item.mcontent}}</view>
					<view>备注：{{item.mremark}}</view>
					<view>保养手册：</view>
					<view v-for="(item,index) in item.mfileList">
								<view style="margin-top: 10px;">	
									<u-button icon="file-text"  @click="viewFile(item)" type="primary" size="small" :plain="true" :hairline="true" text="细边">保养手册{{index+1}}</u-button>
								</view>
					</view>			
				</view>
				<view style="margin-top: 25px;">
					<u-radio-group v-model="item.status" @change="(e) => radioGroupChange(e,item)" size="50rpx">
						<u-radio name="0">完成</u-radio>
						<u-radio name="1">异常</u-radio>
					</u-radio-group>
				</view>
				<view style="border: 1px solid black; margin-top: 10px;" v-if="item.status==1">
					<u--text text="异常描述" align="center" style="background-color:#C0C0C0;"></u--text>
					<u--textarea v-model="item.content" @blur="saveInspepctionInfo(item)" placeholder="请输入内容" autoHeight count
						border="bottom"></u--textarea>
					<u--text text="图片上传：" align="center" style="background-color:#C0C0C0"></u--text>
					<u-upload style="margin-top: 10px;" :fileList="item.imagesList" @afterRead="(event) => afterRead(event,item)"
						@delete="(event) => deletePic(event,item)" name="" multiple :maxCount="3"
						:previewFullImage="true"></u-upload>
				</view>
				<u-line margin="30rpx 0rpx 0rpx 0rpx" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		onLoad
	} from 'uview-ui/libs/mixin/mixin';
	import {
				createFault
			} from '@/api/fault/fault.js';
	import {
		getAppInspectionRecordInfoList,
		updateInspectionRecordInfo
	} from '@/api/deviceInspection/deviceInspection.js';
	import dictTag from '@/components/dict-tag/dict-tag.vue'
	import {
		getAccessToken
	} from "@/utils/auth";
	export default {
		components: {
			dictTag
		},
		data() {
			return {
				// 文件列表是否可选
				fileReadonly: true,
				// 选择日期
				pickerDate: undefined,
				/* 列表数据 */
				deviceSpotList: [],
				/* 查询参数 */
				queryParams: {
					pageNo: 1,
					pageSize: 10,
					deviceId: undefined,
					planId: undefined,
					createTime: [],
					res: 2
				},
			};
		},
		onLoad(option) {
			this.queryParams.planId = option.planId
			this.queryParams.deviceId = option.item.deviceId
			this.pickerDate = new Date().toISOString().slice(0, 10).replace('T', ' ')
			this.changeTime(this.pickerDate)
		},
		computed: {
					reportRepair() {
						let flag = false;
						this.deviceSpotList.forEach(item => {
							if (item.status == "null") {
								flag = false
								return
							}
							if (item.status === '1') {
								flag = true
							}
						})
						return flag
					}
				},
		methods: {
						// 提报报修申请
									reportRepairClick() {
										let form = {
											deviceId: this.queryParams.deviceId,
											code: Date.now(),
											emergent: "1", // 一般紧急
											description: '',
											imgUrl: '',
										}
										this.deviceSpotList.forEach(item => {
											if (item.status === '1') {
												form.description += (" " + item.content)
												item.imagesList.forEach(tmp => {
													form.imgUrl += (tmp.url + ",")
												})
											}
										})
										if(form.imgUrl.charAt(form.imgUrl.length-1) === ','){
											form.imgUrl = form.imgUrl.slice(0,-1)
										}
										createFault(form).then(response => {
											this.$refs.uToast.show({
												type: 'default',
												message: '提报成功',
												complete() {
												}
											})
										})
									},
			viewFile(url){
				uni.navigateTo({
				    url:'pages/work/pdfview/index?url='+url
				})
			},
			// 保存检查项详情数据
			saveInspepctionInfo(item) {
				let imagesTmp = ''
				if (item.imagesList != undefined && item.imagesList.length > 0) {
					if (item.imagesList.length === 1) {
						imagesTmp += item.imagesList[0].url
					} else {
						for (let tmp = 0; tmp < item.imagesList.length; tmp++) {
							imagesTmp += item.imagesList[tmp].url
							if (tmp < item.imagesList.length - 1) {
								imagesTmp += "#"
							}
						}
					}
				}
				updateInspectionRecordInfo({
					"id": item.id,
					"status": item.status,
					"content": item.content,
					"images": imagesTmp
				}).then(response => {})
			},
			// 删除图片
			deletePic(event, item) {
				item.imagesList.splice(event.index, 1)
				this.saveInspepctionInfo(item)
			},
			// 新增图片
			async afterRead(event, entity) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = entity.imagesList.length
				lists.map((item) => {
					entity.imagesList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = entity.imagesList[fileListLen]
					entity.imagesList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				await this.saveInspepctionInfo(entity)
			},
			uploadFilePromise(url) {
				const config = require("@/config.js")
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/admin-api/infra/file/upload',
						filePath: url,
						name: 'file',
						header: {
							Authorization: "Bearer " + getAccessToken()
						},
						formData: {},
						success: (res) => {
							resolve(JSON.parse(res.data).data)
						}
					});
				})
			},
			// 选中任一radio时，由radio-group触发
			radioGroupChange(e, item) {
				item.status = e
				this.saveInspepctionInfo(item)
			},
			/* 时间范围查询条件 */
			changeTime(e) {
				this.pickerDate = e
				this.queryParams.createTime[0] = e + " 00:00:00";
				this.queryParams.createTime[1] = e + " 23:59:59";
				this.getListFun()
			},
			/* 查询设备检查项列表 */
			getListFun() {
				getAppInspectionRecordInfoList(this.queryParams).then(response => {
					this.deviceSpotList = response.data
					// 处理后台传入的图片
					this.deviceSpotList.forEach(item => {
						let images = []
						item.imagesList.forEach(tmp => {
							images.push({
								"url": tmp
							})
						})
						item.imagesList = images
						item.status += ''

						if(item.mmanual!=undefined && item.mmanual!=''){
							let mmanualList = []
							mmanualList = item.mmanual.split(",")
							item.mfileList = mmanualList
						}
					})
				}).catch(response => {})
			}
		}
	}
</script>

<style lang="scss">
	.u-radio {
		margin-left: 30px;
	}

	.container {
		.data-list {
			.search {
				padding: 20rpx 30rpx 20rpx 30rpx;
				background-color: $uni-bg-color;
			}

			.item {
				background-color: $uni-bg-color;
				padding: 30rpx 30rpx 0rpx 30rpx;

				.item-title {
					font-size: $uni-font-size-base;
					font-weight: bold;
					margin-bottom: 15rpx;
				}

				.item-body {
					font-size: $uni-font-size-sm;
					color: $uni-text-color-grey;
				}

				.item-status {
					height: 60rpx;
					line-height: 60rpx;
				}
			}
		}
	}
</style>
